<!--
 * @Author       : xiangmin
 * @File         : 这个主要试一下自定义表单元素如何去校验，用 useInjectFormItemContext 去做校验
 * @Date         : 2023-11-17 19:20:08
 * @LastEditors  : xiangmin
 * @LastEditTime : 2023-11-17 22:05:59
-->
<template>
	<section v-cloak>
		<a-input
			v-model:value="tag"
			@blur="onFieldBlur"
			v-bind="fieldProps"
		>
			<template #addonAfter>
				<PlusOutlined @click="handleAddClick" />
			</template>
		</a-input>
		<a-space
			wrap
			:size="0"
			class="mt-5"
		>
			<a-tag
				closable
				v-for="(value, index) in tags"
				:key="value"
				@close="handleClose(index)"
			>
				{{ value }}
			</a-tag>
		</a-space>
	</section>
</template>

<script setup lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue'
import { useInjectFormItemContext } from 'ant-design-vue/es/form'

const props = defineProps<{
	fieldProps?: Record<string, any>
	modelValue?: string[]
}>()
const emits = defineEmits<{
	'update:modelValue': [string[]]
}>()

const { onFieldChange, onFieldBlur } = useInjectFormItemContext()
const tag = ref('')
const tags = ref<string[]>([])
props.modelValue && (tags.value = props.modelValue)
const handleAddClick = () => {
	if (!tag.value || tags.value.includes(tag.value)) return
	tags.value.push(tag.value)
	tag.value = ''
	emits('update:modelValue', tags.value)
	onFieldBlur()
}
const handleClose = index => {
	tags.value.splice(index, 1)
	emits('update:modelValue', tags.value)
	onFieldChange()
}
</script>
